package handlers

import (
    "net/http"

    "github.com/gin-gonic/gin"

    "github.com/samaa/photosalesplus/backend/internal/services"
)

type PaymentHandler struct { svc services.PaymentService }

func NewPaymentHandler(s services.PaymentService) *PaymentHandler { return &PaymentHandler{svc: s} }

type createSessionRequest struct {
    OrderID uint   `json:"order_id" binding:"required"`
    Channel string `json:"channel" binding:"required"`
}

func (h *PaymentHandler) CreateSession(c *gin.Context) {
    var req createSessionRequest
    if err := c.ShouldBindJSON(&req); err != nil { c.JSON(http.StatusBadRequest, APIResponse{Error: err.Error()}); return }
    sess, qr, err := h.svc.CreateSession(c.Request.Context(), req.OrderID, services.PaymentChannel(req.Channel))
    if err != nil { respondError(c, http.StatusInternalServerError, err); return }
    c.JSON(http.StatusOK, APIResponse{Data: gin.H{
        "session": sess,
        "qrcode":  qr,
    }})
}

func (h *PaymentHandler) GetSession(c *gin.Context) {
    id := c.Param("id")
    sess, err := h.svc.GetSession(c.Request.Context(), id)
    if err != nil { c.JSON(http.StatusNotFound, APIResponse{Error: "session not found"}); return }
    c.JSON(http.StatusOK, APIResponse{Data: sess})
}

// Placeholder callbacks for later integration
func (h *PaymentHandler) CallbackWeChat(c *gin.Context) {
    id := c.Query("session_id")
    if id == "" { c.JSON(http.StatusBadRequest, APIResponse{Error: "missing session_id"}); return }
    if err := h.svc.MarkPaid(c.Request.Context(), id); err != nil { respondError(c, http.StatusInternalServerError, err); return }
    c.JSON(http.StatusOK, APIResponse{Message: "ok"})
}

func (h *PaymentHandler) CallbackAlipay(c *gin.Context) { h.CallbackWeChat(c) }

